package com.atguigu.gmall.common.config.service;


import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.constant.MqCons;
import com.atguigu.gmall.common.config.entity.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;



    //发消息  第一次发消息使用下面的方法  会生成UUID及相关数据 封装成对象  作为发消息失败后 的返回值
    public void sendMessage(String exchange,String routingKey,Object message){

        //封装对象 为了当发送消息不成功时 作为返回值对象 （有此返回值对象 可以再次找机会发消息）
        GmallCorrelationData correlationData = new GmallCorrelationData();
        String correlationId  = UUID.randomUUID().toString();
        correlationData.setId(correlationId );
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(message);

        redisTemplate.opsForValue().set(correlationId,
                JSON.toJSONString(correlationData), MqCons.OBJECT_TIME, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
    }


    public void sendDelayMessage(String exchangeDirectOrderCancel, String routingOrderCancel,
                                 Object message, int delayTime) {

        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String correlationId = UUID.randomUUID().toString();
        gmallCorrelationData.setId(correlationId);
        gmallCorrelationData.setMessage(message);
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setExchange(exchangeDirectOrderCancel);
        gmallCorrelationData.setRoutingKey(routingOrderCancel);
        gmallCorrelationData.setDelayTime(delayTime);

        redisTemplate.opsForValue().set(correlationId,
                JSON.toJSONString(gmallCorrelationData), MqCons.OBJECT_TIME, TimeUnit.MINUTES);

        System.out.println("保存延迟消息：" + JSON.toJSONString(gmallCorrelationData));

        rabbitTemplate.convertAndSend(MqCons.EXCHANGE_DIRECT_ORDER_CANCEL,MqCons.ROUTING_ORDER_CANCEL,
                message,m -> {
                    m.getMessageProperties().setDelay(delayTime);
                    return m;
                },gmallCorrelationData);
    }
}
